package com.emergency.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.emergency.http.DefaultResponseCode;
import com.emergency.http.WrapMapper;
import com.emergency.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtUtil.AUTH_HEADER_KEY);
        if (StrUtil.isBlank(authHeader)) {
            returnJson(response, JSON.toJSONString(WrapMapper.wrap(DefaultResponseCode.NOT_LOGGED_IN)));
            return false;
        }
        try {
            //获取token、
            String token;
            if (authHeader.startsWith("Bearer")) {
                token = authHeader.substring(7);
            } else {
                token = authHeader;
            }
            //解析token
            JwtUtil.parseJWT(token);
        } catch (ExpiredJwtException e) {
            returnJson(response, JSON.toJSONString(WrapMapper.wrap(DefaultResponseCode.TOKEN_TIME_OUT)));
            return false;
        } catch (Exception e) {
            returnJson(response, JSON.toJSONString(WrapMapper.wrap(DefaultResponseCode.TOKEN_PARSE_EXCEPTION)));
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
